package wish.regularExpression;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class DisjunctiveElement extends RegularExpressionElement {

	private ArrayList<RegularExpressionElement> list;

	public DisjunctiveElement(){
		
		list = new ArrayList<RegularExpressionElement>();
		
	}
	
	public void addElement(RegularExpressionElement regularExpression){
		
		list.addAll(regularExpression.getMachingElements());
	
		Collections.sort(list, new Comparator<RegularExpressionElement>(){

			@Override
			public int compare(RegularExpressionElement arg0,
					RegularExpressionElement arg1) {
				return arg0.toString().compareTo(arg1.toString());
			}
			
		});
		
	}
	
	@Override
	public boolean matches(RegularExpressionElement regExpele) {
		
		for (RegularExpressionElement element : list) {
			
			if (element.matches(regExpele)){
				return true;
			}
			
		}
		
		return false;
		
	}

	@Override
	public List<RegularExpressionElement> getMachingElements() {
		return list;
	}

	public String toString(){

		String ret = "(" + list.get(0);
		
		for (int i = 1; i < list.size(); i++) {
			
			ret = ret + "|" + list.get(i);
			
		}
		
		return ret + ")";
	}

	@Override
	protected RegularExpressionElement expandWithMatchingRegularExpression(
			RegularExpressionElement regExp) {
		
		//it gets here only when match. No empty
		
		Iterator<RegularExpressionElement> iterator = list.iterator();
		
		List<RegularExpressionElement> newList = new ArrayList<RegularExpressionElement>();
		
		while (iterator.hasNext()){
			
			RegularExpressionElement reg = iterator.next();
			
			newList.add(reg.expand(regExp));
			
		}
		
		list.clear();
		
		list.addAll(newList);
		
		newList.clear();
		
		return this;
		
	}
	
}
